package com.itheima.up_web.service.impl;

import cn.itcast.up.common.ConfigHolder;
import cn.itcast.up.common.OozieParam;
import cn.itcast.up.common.OozieUtils;
import com.itheima.up_web.bean.dto.ModelDto;
import com.itheima.up_web.bean.po.ModelPo;
import com.itheima.up_web.bean.repo.ModelRepository;
import com.itheima.up_web.service.Engine;
import lombok.SneakyThrows;
import org.apache.oozie.client.OozieClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.Properties;

@Service
public class EngineImpl implements Engine {
    @Autowired
    private ModelRepository modelRepository;

    @Override
    public String startModel(ModelDto modelDto) {

        OozieParam param = new OozieParam(
                modelDto.getId(),
                modelDto.getMainClass(),
                modelDto.getPath(),
                modelDto.getArgs(),
                ModelDto.Schedule.formatTime(modelDto.getSchedule().getStartTime()),
                ModelDto.Schedule.formatTime(modelDto.getSchedule().getEndTime())
        );
        System.out.println(param);
        Properties prop = OozieUtils.genProperties(param);
        OozieUtils.uploadConfig(modelDto.getId());
        OozieUtils.store(modelDto.getId(), prop);
        String jobId = OozieUtils.start(prop);
        return jobId;
    }

    @SneakyThrows
    @Override
    public void stopModel(ModelDto modelDto) {
        OozieClient oozieClient = new OozieClient(ConfigHolder.oozie().url());
        Optional<ModelPo> modelPo = modelRepository.findById(modelDto.getId());
        oozieClient.kill(modelPo.get().getJobId());
    }
}
